package com.easydl.project.amqp.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.easydl.project.amqp.model.EasydlDiscernMessageVO;

@Service
public class EasydlAmqpService {
	
	
	private Logger logger=LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	final RabbitTemplate.ConfirmCallback confirmCallback=new RabbitTemplate.ConfirmCallback() {
		
		@Override
		public void confirm(CorrelationData correlationData, boolean ack, String cause) {
			logger.info("ack确认:"+ack);
		}
	};
	
	final RabbitTemplate.ReturnCallback returnCallback =new RabbitTemplate.ReturnCallback() {
		/**
		 * 如果mandatory有设置，则当消息不能路由到队列中去的时候，会触发return method。
		 * 如果mandatory没有设置，则当消息不能路由到队列的时候，server会删除该消息。
		 */
		@Override
		public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
			logger.info("return exchange: " + exchange + ", routingKey: "
                    + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
		}
	};
	
	
	public void sendEasydlDiscernMessage(EasydlDiscernMessageVO easydlDiscernMessageVO) {
		rabbitTemplate.setMandatory(true);
	    rabbitTemplate.setConfirmCallback(confirmCallback);
	    rabbitTemplate.setReturnCallback(returnCallback);
		rabbitTemplate.convertAndSend("easydlDiscern", "easyMask", easydlDiscernMessageVO);
	}
	
	public void sendMessageNack(String message) {
		rabbitTemplate.setMandatory(true);
	    rabbitTemplate.setConfirmCallback(confirmCallback);
	    rabbitTemplate.setReturnCallback(returnCallback);
		rabbitTemplate.convertAndSend("margoRabbitExchange", "margoRabbit", message);
	}
}
